package com.norma.netty.study.netty.disruptor;

import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.dsl.ProducerType;
import com.norma.netty.study.netty.disruptor.core.RingBufferWorkerPoolFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.util.ArrayList;

/**
 * @author zhangchaofeng
 * @date 2021/1/5
 * @description
 */
public class NettyServer {

    public static void main(String[] args) {
        ArrayList<MessageConsumerImpl4Server> messageConsumerImpl4Servers = new ArrayList<>();
        messageConsumerImpl4Servers.add(new MessageConsumerImpl4Server("1"));
        messageConsumerImpl4Servers.add(new MessageConsumerImpl4Server("2"));
        MessageConsumerImpl4Server[] messageConsumerImpl4Servers1
                = messageConsumerImpl4Servers.toArray(new MessageConsumerImpl4Server[2]);
        RingBufferWorkerPoolFactory.getInstance().initAndStart(ProducerType.MULTI, 1024,
                new BlockingWaitStrategy(), messageConsumerImpl4Servers1);
        //Start Netty Server
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap b;
        try {
            b = new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    //TCP缓冲区设置 操作系统底层tcp连接过来了，有SYNC(正在连接的队列)队列
                    //和ACCEPT队列(存放已经三次握手成功的连接)
                    //sync + accept = backlog 数量
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //NIO接收和发送数据都会把数据缓存到buffer，
                    // 可以根据实际情况指定分配的大小（太大浪费内存，太小不够用）
                    //还可以使用缓存区动态调配（自适应，适合用在数据包大小差不多的场景）
                    .option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
                    //缓冲对象池
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    //netty打印日志
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
                            pipeline.addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });
            Channel channel = b.bind("127.0.0.1", 9998).channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
